package com.fjnldx.mes.service.alarm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjnldx.mes.domain.domainReq.Id;
import com.fjnldx.mes.domain.domainReq.alarm.QueryAlarmRecordPageReq;
import com.fjnldx.mes.domain.domainRes.Result;
import com.fjnldx.mes.domain.domainRes.ResultObject;
import com.fjnldx.mes.domain.domainRes.alarm.AlarmRecordCountRes;
import com.fjnldx.mes.domain.domainRes.alarm.AlarmRecordStatisticalRes;
import com.fjnldx.mes.domain.pojo.alarm.AlarmRecord;
import com.fjnldx.mes.domain.pojo.alarm.enums.TriggerStatusEnum;
import com.fjnldx.mes.mapper.alarm.AlarmRecordMapper;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AlarmRecordService {

    @Resource
    private AlarmRecordMapper alarmRecordMapper;

    /**
     * 获取告警数量
     *
     * @return 告警数量
     * @throws Exception 未知异常
     */
    public Result getRecordCount(LocalDate startTime, LocalDate endTime) throws Exception {
        try {
            QueryWrapper<AlarmRecord> queryWrapper = new QueryWrapper<>();
            if (null != startTime) {
                queryWrapper.ge("createTime", startTime);
            }
            if (null != endTime) {
                queryWrapper.le("createTime", endTime.plusDays(1));
            }
            queryWrapper.select("status,dicBh");
            List<AlarmRecord> records = alarmRecordMapper.selectList(queryWrapper);
            AlarmRecordCountRes result = new AlarmRecordCountRes();
            result.setTotal(records.size());
            result.setAbnormal((int) records.stream().filter(record -> record.getStatus() == TriggerStatusEnum.ABNORMAL).count());
            result.setNormal((int) records.stream().filter(record -> record.getStatus() == TriggerStatusEnum.NORMAL).count());
            List<String> gongXuList = new ArrayList<>();
            gongXuList.add("细纱");
            gongXuList.add("粗纱");
            gongXuList.add("络筒");
            gongXuList.add("抓棉");
            gongXuList.add("并条");
            gongXuList.add("梳棉");
            gongXuList.add("开棉");
            gongXuList.add("多仓");
            result.setEquipment((int) records.stream().filter(record -> gongXuList.contains(record.getDicBh())).count());
            List<String> fujiList = new ArrayList<>();
            fujiList.add("电表");
            fujiList.add("温湿度");
            fujiList.add("空压机");
            result.setAuxiliary((int) records.stream().filter(record -> fujiList.contains(record.getDicBh())).count());
            result.setPower((int) records.stream().filter(record -> Objects.equals(record.getDicBh(), "耗电")).count());
            return Result.success(result);
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 获取告警记录列表
     *
     * @return 告警记录列表
     * @throws Exception 未知异常
     */
    public Result getRecordPages(QueryAlarmRecordPageReq param) throws Exception {
        try {
            //条件拼接
            QueryWrapper<AlarmRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("createTime");
            if (!StringUtils.isEmpty(param.getDicBh()) && !"null".equals(param.getDicBh())) {
                queryWrapper.like("dicBh", param.getDicBh());
            }
            if (!StringUtils.isEmpty(param.getDevSn()) && !"null".equals(param.getDevSn())) {
                queryWrapper.like("devSn", param.getDevSn());
            }
            if (null != param.getLevel()) {
                queryWrapper.eq("level", param.getLevel());
            }
            //分页查询
            Page<AlarmRecord> page = new Page<>(param.getPageNum(), param.getPageSize());
            IPage<AlarmRecord> result = alarmRecordMapper.selectPage(page, queryWrapper);
            //封装返回结果
            ResultObject<AlarmRecord> res = new ResultObject<>();
            res.setDataList(result.getRecords());
            res.setTotal((int) result.getTotal());
            return Result.success(res);
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 关闭告警
     *
     * @param param 告警标识
     * @return 处理结果
     * @throws Exception 未知异常
     */
    public Result turnOffAlarm(Id param) throws Exception {
        try {
            AlarmRecord alarmRecord = alarmRecordMapper.selectById(param.getId());
            alarmRecord.setStatus(TriggerStatusEnum.NORMAL);
            alarmRecordMapper.updateById(alarmRecord);
            return Result.success("关闭成功");
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 告警统计
     *
     * @return 告警统计结果
     */
    public Result getStatistical(List<String> dicBhs, LocalDate startTime, LocalDate endTime) throws Exception {
        try {
            QueryWrapper<AlarmRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("dicBh", dicBhs);
            queryWrapper.orderByDesc("createTime");
            queryWrapper.select("dicBh");
            if (null != startTime) {
                queryWrapper.ge("createTime", startTime);
            }
            if (null != endTime) {
                queryWrapper.le("createTime", endTime.plusDays(1));
            }
            List<AlarmRecord> alarmRecordList = alarmRecordMapper.selectList(queryWrapper);
            List<AlarmRecordStatisticalRes> result = dicBhs.stream()
                    .map(dicBh -> new AlarmRecordStatisticalRes(dicBh, alarmRecordList.stream().filter(record -> record.getDicBh().equals(dicBh)).count()))
                    .collect(Collectors.toList());
            return Result.success(result);
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 获取统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 统计结果
     * @throws Exception 未知异常信息
     */
    public Result getLevelStatistical(LocalDate startTime, LocalDate endTime) throws Exception {
        try {
            QueryWrapper<AlarmRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("createTime");
            queryWrapper.select("level");
            if (null != startTime) {
                queryWrapper.ge("createTime", startTime);
            }
            if (null != endTime) {
                
                queryWrapper.le("createTime", endTime.plusDays(1));
            }
            List<AlarmRecord> alarmRecordList = alarmRecordMapper.selectList(queryWrapper);
            List<AlarmRecordStatisticalRes> result = alarmRecordList.stream()
                    .collect(Collectors.groupingBy(AlarmRecord::getLevel, Collectors.counting()))
                    .entrySet().stream()
                    .map(entry -> new AlarmRecordStatisticalRes(entry.getKey().toString(), entry.getValue()))
                    .collect(Collectors.toList());
            return Result.success(result);
        } catch (Exception e) {
            throw new Exception();
        }
    }
}
